import React, { ReactText, useRef, useState } from 'react';
import { Form, Button, Input, Modal, InputNumber } from 'antd';
import { createSyntheticTTSVoice, getTTSInfo, getTTSList } from 'admin/servers/servers';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';
import { SyntheticTTSVoice } from 'admin/schema/TTS';
import { verifyNull } from 'utils/tools';

type Props = {
  loading: boolean;
  /**上传文件夹id */
  fileId: number;
  /**TTS配置数据上屏显示 */
  configInfo: any;
  disabled?: boolean;
  /**成功回调 */
  callback: (file: any, newConfig: SyntheticTTSVoice) => void;
};

/**配置TTS合成语音 */
export const ConfigSoundTTS: React.FC<Props> = ({
  loading,
  fileId,
  configInfo,
  disabled,
  callback,
}) => {
  /**录音播放-ref */
  const [form] = Form.useForm();
  const ttsSelectRef = useRef<any>();
  // 弹窗显示
  const [visible, setVisible] = useState<boolean>(false);

  /**配置弹窗打开 */
  const openModel = () => {
    // TTS默认配置
    const obj = configInfo as SyntheticTTSVoice;
    setVisible(true);
    if (obj) {
      // 弹窗，需要初始化表单数据，赋值
      form.setFieldsValue(obj);
      // 根据ttsId查找 - 回显;
      setTimeout(() => {
        const { ttsId } = obj;
        if (ttsId) {
          const ttsManufacturerId = ttsId;
          ttsSelectRef.current?.setValue(ttsManufacturerId as number);
        }
      }, 0);
    }
  };
  const handleOK = () => {
    form.validateFields().then(() => {
      console.log('表单验证通过');
      // 表单验证通过
      const val = form.getFieldsValue() as SyntheticTTSVoice;
      // 请求接口-创建新的音频文件
      createSyntheticTTSVoice(val)
        .then(blob => {
          // 拿到后端返回的音频文件流file
          const fb = blob;
          const file = new File([fb], '合成音频.wav', {
            type: fb.type,
          });
          console.log('合成录音-', file);
          // 进行下一步：上传文件
          callback(file, val);
          // 关闭弹窗
          handleClose();
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };

  const handleClose = () => {
    console.log('点击-关闭');
    // 恢复默认
    form.resetFields();
    setVisible(false);
  };

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };

  /**
   * 查找TTS厂商的dataProvider
   */
  const fetchTTS = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getTTSList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        ttsManufacturerName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.ttsManufacturerName,
                value: item.ttsManufacturerId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数
   */
  const fetchTTSRecord = (ttsManufacturerId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getTTSInfo(ttsManufacturerId as number).then(res => {
        const item = res.data;
        resolve({
          label: item.ttsManufacturerName,
          value: item.ttsManufacturerId,
          data: item, // 便于onChange判断，有data则回显赋值不用更新数据
        });
      });
    });
  };
  return (
    <div className="upload-wrap">
      <Button
        type="primary"
        loading={loading}
        onClick={() => {
          openModel();
        }}
      >
        配置TTS
      </Button>
      {/* 播放 */}
      <Modal
        title="配置TTS"
        visible={visible}
        onOk={handleOK}
        onCancel={handleClose}
        okButtonProps={{ disabled: disabled }}
      >
        <Form {...layout} form={form} layout="horizontal">
          <Form.Item
            label="提示内容"
            name="text"
            rules={verifyNull('请输入提示内容')}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input.TextArea placeholder="请输入300以内字符" maxLength={300} disabled={disabled} />
          </Form.Item>
          <Form.Item label="音色" name="ttsId" rules={verifyNull('请选择音色')}>
            <PageSelect
              key="ttsSelect"
              ref={ttsSelectRef}
              fetchData={fetchTTS}
              placeholder="请选择音色"
              fetchRecord={fetchTTSRecord}
              allowClear
              disabled={disabled}
            />
          </Form.Item>
          <Form.Item label="音量" name="volume" rules={verifyNull('请选择音量')}>
            <InputNumber
              min={1}
              max={100}
              precision={0}
              placeholder="请输入音量"
              style={{ width: 200, marginRight: '5px' }}
              disabled={disabled}
            />
          </Form.Item>
          <Form.Item label="语速" name="speechSpeed" rules={verifyNull('请选择语速')}>
            <InputNumber
              min={-500}
              max={500}
              precision={0}
              placeholder="请输入语速"
              style={{ width: 200, marginRight: '5px' }}
              disabled={disabled}
            />
          </Form.Item>
          <Form.Item label="语调" name="intonation" rules={verifyNull('请选择语调')}>
            <InputNumber
              min={-500}
              max={500}
              precision={0}
              placeholder="请输入语调"
              style={{ width: 200, marginRight: '5px' }}
              disabled={disabled}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
